package com.example.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.example.SpringbootQuickstartApplication;
import com.example.domain.Book;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;

import javax.annotation.Resource;
import java.util.List;

//测试类需要在引导类所在包及其子包中，不然就得指定引导类，以下两种方式均可以
//@SpringBootTest(classes = SpringbootQuickstartApplication.class)
//@ContextConfiguration(classes = SpringbootQuickstartApplication.class)
@SpringBootTest
public class BookDaoTestCase {

    @Resource
    private BookDao bookDao;

    /**
     * 新增
     */
    @Test
    void testSave(){
        Book book = new Book();
        book.setType("计算机书籍");
        book.setName("C Primer Plus，5th Edition");
        book.setDescription("【美】Stephen Prata著");
        bookDao.insert(book);
    }

    /**
     * 修改
     */
    @Test
    void testUpdate(){
        Book book = new Book();
        book.setId(13);
        book.setType("计算机书籍");
        book.setName("C Primer Plus，5th Edition~");
        book.setDescription("【美】Stephen Prata著");
        bookDao.updateById(book);
    }

    /**
     * 删除
     */
    @Test
    void testDelete(){
        bookDao.deleteById(13);
    }

    /**
     * 查询单条记录
     */
    @Test
    void testGetById(){
        bookDao.selectById(12);
    }

    /**
     * 查询全部
     */
    @Test
    void testGetAll(){
        List<Book> books = bookDao.selectList(null);
    }

    /**
     * 分页查询（Ctrl+H查询全部实现类）
     */
    @Test
    void testSelectPage(){
        IPage<Book> page = new PageDTO<>(1,5);
        bookDao.selectPage(page,null);
        System.out.println(page.getCurrent());  //当前页码值
        System.out.println(page.getSize());     //每页数据总量
        System.out.println(page.getTotal());    //数据总量
        System.out.println(page.getRecords());  //数据
        System.out.println(page.getPages());    //最大页码值
    }

    /**
     * 按条件查询
     */
    @Test
    void testGetByCondition(){
        String name = "MYSQL";
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.like("name",name);
        List<Book> books = bookDao.selectList(wrapper);
    }

    /**
     * 动态拼接查询条件，优化非空判断
     */
    @Test
    void testQueryByLambdaCondition(){
        String name = "MYSQL";
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        lqw.like(name!=null,Book::getName,name);
        List<Book> books = bookDao.selectList(lqw);
    }

}